/**
 * 人员-多选.
 *
 * @Creator      : liujiedong
 * @Create Date  : 2018-4-3
 * @Since        : 06.00.0000
 * Modifier      :
 * Modified Date :
 * @Dependences  : appcan.js, jquery.js, vue.js, supp*.js
 * @Description  :
 */

// ~ Fields
// ====================================================================================================================
var vueObj;
//部门列表
var deptList;
//当前部门节点
var currentDeptNode;
//父级节点
var parentDic = {};

var emp1 = [{
    pDeptId : "1",
    empId : "11",
    empImg : "img/4.png",
    empName : "技术1",
    position : "总经理"
}, {
    pDeptId : "1",
    empId : "22",
    empImg : "img/4.png",
    empName : "技术2",
    position : "总经理"
}],
    emp2 = [{
    pDeptId : "2",
    empId : "33",
    empImg : "img/4.png",
    empName : "产品1",
    position : "总经理"
}, {
    pDeptId : "2",
    empId : "44",
    empImg : "img/4.png",
    empName : "产品2",
    position : "总经理"
}];

var empList = [];

var empDeptList = [];

var empSelected = [],
    deptSelected = [];
var confirmBtnDisabled = true;

// ~ Initialize
// ====================================================================================================================
jq(function() {
    initVue();
    window.setTimeout(function() {
        initEvent();
    }, 300);

    initData();
    initPage();
    initPageName();
});

// ~ Public Functions
// ====================================================================================================================

//给object对象数组增加一个方法，根据object中的主键属性值(可作为主键的属性),从数组中移除该对象
Array.prototype.removeByPrimaryKey = function(key, val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i][key] == val) {
            this.splice(i, 1);
            break;
        }
    }
}
//给object对象数组增加一个方法，根据object中的主键属性值(可作为主键的属性)查找该对象
Array.prototype.findByPrimaryKey = function(key, val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i][key] == val) {
            return this[i];
        }
    }

}
//克隆array
Array.prototype.clone = function() {
    return this.slice(0);

}
// ~ Private Functions
// ====================================================================================================================
//初始化页面事件
function initEvent() {
    $(".icon-fa-back").unbind("click").on("click", function() {
        //判断showType是否为false，如果是，则表明进入到了部门的下一级
        //点击返回，实际是返回部门的上一级
        if (vueObj.showType == false) {
            if (!parentDic.pId) {
                //如果父级没有pid，则说明父级是根节点，showType设为true
                vueObj.showType = true;
            }
            //根据pid查询pid对应的部门详情
            parentDic = deptList.findByPrimaryKey("id", parentDic.pId);
            $(".supp-header-title").html(parentDic.name);
            //根据父节点id的pid查询所有部门
            //查询所有子部门
            var sonList = [];
            sonList = jq.map(deptList, function(item) {
                if (item.pId == parentDic.id) {
                    item["checked"] = false;
                    return item;
                }
            });
            parentDic["son"] = sonList;

            //异步查询当前部门的下级所有人员
            getEmpListAllByDeptNode(parentDic.id);

            //部门列表默认显示根节点下的一级部门
            for (var i = 0; i < parentDic.son.length; i++) {
                var node = parentDic.son[i];
                var _sonList = [];
                _sonList = jq.map(deptList, function(item) {
                    if (item.pId == node.id) {
                        item["checked"] = false;
                        return item;
                    }
                });
                node["son"] = _sonList;
                node["emp_all"] = [];
                //异步查询当前部门的下级所有人员
                getEmpListAllByDeptNode(node.id, i);
            };
            empDeptList = parentDic.son;
            vueObj.empDeptList = parentDic.son;

            //得到当前节点下的人员列表
            getEmpListByDeptNode(parentDic.id);

        } else {
            Supp.UI.closeWindow();
        }

    });

}

//设置部门是否选中
function setItemChecked(item) {
    var selectedList = vueObj.deptSelected;
    item["checked"] = false;
    for (var j = 0; j < selectedList.length; j++) {
        var selectedItem = selectedList[j];
        if (selectedItem.id == item.id) {
            item["checked"] = true;
            break;
        }
    };
}

function initVue() {
    vueObj = new Vue({
        el : "#content1",
        data : {
            empList : empList,
            empDeptList : empDeptList,
            empSelected : empSelected,
            deptSelected : deptSelected, //部门选择
            confirmBtnDisabled : confirmBtnDisabled,
            showType : true,
            sonDeptEmpNum : 0
        },
        methods : {
            checkedEmp : function(item) {
                var empId = item.empId;
                //选中和取消个别人员
                if (item.checked) {
                    vueObj.removeEmp(empId, item);
                } else {
                    var emp = this.empSelected.findByPrimaryKey("empId", item.empId);
                    item.checked = true;
                    //用户已存在，则不再添加
                    if (emp && emp.empId) {
                        return;
                    }

                    this.empSelected.push(item);
                    this.changeConfirmBtn();

                    setTimeout(function() {
                        slideCheckedDiv();
                    }, 100);

                }
            },
            checkedDept : function(item, index) {//选中和取消部门下面的人员
                var deptId = item.id;
                var me = this;
                //已被选中，则取消该部门下所有人员
                if (item.checked) {
                    Supp.UI.confirm({
                        title : " ",
                        msg : "取消该部门意味着取消该部门下的所有成员（包括子部门下成员）",
                        ok : "确定",
                        cancel : "取消",
                        //isAppcan:true,
                        onOk : function(argument) {
                            item.checked = false;
                            var allEmpList = vueObj.empDeptList[index].emp_all;
                            var selectedList = me.empSelected;
                            //当前vue中的选中人员
                            var empList = vueObj.empList;
                            for (var i = 0; i < allEmpList.length; i++) {
                                var cancelEmp = allEmpList[i];
                                selectedList.removeByPrimaryKey("empId", cancelEmp.empId);
                                empSelected.removeByPrimaryKey("empId", cancelEmp.empId);
                                var emp = empList.findByPrimaryKey("empId", cancelEmp.empId);
                                if (emp && emp.empId) {
                                    emp["checked"] = false;
                                }
                            };

                            me.removeDept(deptId);

                            me.changeConfirmBtn();

                            setTimeout(function() {
                                slideCheckedDiv();
                            }, 100);
                        }
                    });
                } else {
                    //没被选中，则选中该部门下所有人员
                    var dept = this.deptSelected.findByPrimaryKey("id", item.id);
                    if (dept && dept.id) {
                        return;
                    }
                    Supp.UI.confirm({
                        title : " ",
                        msg : "选中该部门意味着选中该部门下的所有成员（包括子部门下成员）",
                        ok : "确定",
                        cancel : "取消",
                        //isAppcan:true,
                        onOk : function(argument) {
                            var allEmpList = vueObj.empDeptList[index].emp_all;
                            var allEmpList_clone = allEmpList.clone();
                            var selectedList = me.empSelected;
                            //当前vue中的选中人员
                            var empList = vueObj.empList;
                            for (var i = 0; i < allEmpList.length; i++) {
                                var emp = allEmpList[i];
                                emp["checked"] = true;
                            };

                            for (var i = 0; i < selectedList.length; i++) {
                                var selectedEmp = selectedList[i];
                                allEmpList_clone.removeByPrimaryKey("empId", selectedEmp.empId);
                            };
                            selectedList = selectedList.concat(allEmpList_clone);

                            me.empSelected = selectedList;
                            empSelected = selectedList;
                            item.checked = true;

                            me.deptSelected.push(item);

                            me.changeConfirmBtn();

                            setTimeout(function() {
                                slideCheckedDiv();
                            }, 100);
                        }
                    });

                }
            },
            removeEmp : function(empId, item) {

                // for (var i = 0; i < this.empSelected.length; i++) {
                // if (empId == this.empSelected[i].empId) {
                // this.empSelected[i].checked = false;
                // this.empSelected.splice(i, 1);
                // }
                // }
                //
                //通过选择部门添加的人员
                if (item.addWay == "dept") {
                    // var pDeptId = item.deptId;
                    // for (var i = 0; i < this.empSelected.length; i++) {
                    // if (this.empSelected[i].deptId == pDeptId) {
                    // return false;
                    // }
                    // }
                    //
                    // for (var i = 0; i < this.deptSelected.length; i++) {
                    // if (pDeptId == this.deptSelected[i].deptId) {
                    // this.deptSelected[i].checked = false;
                    // this.deptSelected.splice(i, 1);
                    // }
                    // }
                }
                item.checked = false;
                this.empSelected.removeByPrimaryKey("empId", empId);
                this.changeConfirmBtn();

                setTimeout(function() {
                    slideCheckedDiv();
                }, 100);
            },
            removeDept : function(id) {
                this.deptSelected.removeByPrimaryKey("id", id);
            },
            changeConfirmBtn : function(isIndexed) {
                if (this.empSelected.length > 0) {
                    this.confirmBtnDisabled = false;
                } else {
                    this.confirmBtnDisabled = true;
                }
                if (!isIndexed) {
                    $(".supp-table-view .supp-checkbox").each(function(i, n) {
                        $(n).find("input").prop("checked", false);
                    });

                    for (var i = 0; i < this.empSelected.length; i++) {
                        $(".supp-table-view").find("#checkbox_" + this.empSelected[i].empId).prop("checked", true);
                    }
                }

            },
            showLowerBtn : function(model) {
                parentDic = model;
                this.showType = false;
                $(".supp-header-title").html(model.name);

                //查询所有的下级人员总数
                this.empDeptList = model.son;
                this.empList = [];
                var empAllList = model.emp_all;
                if (empAllList && empAllList.length > 0) {
                    this.sonDeptEmpNum = empAllList.length;
                } else {
                    this.sonDeptEmpNum = 0;
                }

                //遍历所有下级部门，查询是否存在子部门
                for (var i = 0; i < model.son.length; i++) {
                    var node = model.son[i];

                    var sonList = jq.map(deptList, function(item) {
                        if (item.pId == node.id) {
                            setItemChecked(item);
                            return item;
                        }
                    });
                    node["son"] = sonList;
                    node["emp_all"] = [];
                    //异步查询当前部门的下级所有人员
                    getEmpListAllByDeptNode(node.id, i);
                };
                //查询当前节点人员信息
                getEmpListByDeptNode(model.id);

            },
            confirmBtn : function() {
                var returnVal = {},
                    empsName = [],
                    empsId = [];

                for (var i = 0; i < this.empSelected.length; i++) {
                    empsName.push(this.empSelected[i].empName);
                    empsId.push(this.empSelected[i].empId);
                }

                returnVal["empsName"] = empsName.join(",");
                returnVal["empsId"] = empsId.join(",");

                var empsDeptId = [];
                for (var i = 0; i < this.deptSelected.length; i++) {
                    empsDeptId.push(this.deptSelected[i].id);
                }
                returnVal["empsDeptId"] = empsDeptId.join(",");

                appcan.window.publish("emp_multi_choose", JSON.stringify(returnVal));
                appcan.window.close();

            },
        }
    });
}

//初始化字母索引页面
function initPageName() {
    Supp.IndexedList.init({
        renderTo : "list", //id
        url : "/service/mobile/proxy/r/service/eip/employee/getEmpListWithPinyin",
        chkStyle : "checkbox", //radio/checkbox
        hasImg : true,
        callBack : function() {
            $(".supp-table-view .supp-list-content").click(function() {
                var val = $(this).parent().find("input").prop("checked");
                var empId = $(this).parent().find("input").val();
                var item = null;
                for (var i = 0; i < vueObj.empList.length; i++) {
                    if (empId == vueObj.empList[i].empId) {
                        item = vueObj.empList[i];
                    }
                }
                var item = item;

                vueObj.checkedEmp(item, empId);

                if (val) {
                    $(this).parent().find("input").prop("checked", false);
                } else {
                    $(this).parent().find("input").prop("checked", true);
                }
                vueObj.changeConfirmBtn(true);
            });
        }
    });
}

function initData() {
    var _checkedVal = Supp.LocStorage.getVal("meip_emp_multi_checked");
    if (!_checkedVal) {
        return;
    }
    var checkedVal = JSON.parse(_checkedVal);
    if (checkedVal && checkedVal.length == 0) {
        return;
    }
    var checkedEmpArr = checkedVal.empsId.split(",");
    //通过人员选择的
    for (var i = 0; i < checkedEmpArr.length; i++) {
        for ( j = 0; j < empList.length; j++) {
            if (empList[j].empId == checkedEmpArr[i]) {
                empList[j].checked = true;
                empSelected.push(empList[j]);
                confirmBtnDisabled = false;
            }
        }
    }

    var checkedEmpArr = checkedVal.empsDeptId.split(",");

    //通过部门选择的
    for (var i = 0; i < checkedEmpArr.length; i++) {
        for ( j = 0; j < empDeptList.length; j++) {
            if (empDeptList[j].deptId == checkedEmpArr[i]) {
                empDeptList[j].checked = true;

                //查找子元素,例如子元素为emp1
                empSelected = empSelected.concat(emp1);

                confirmBtnDisabled = false;
            }
        }
    }
}

function initPage() {
    //获取根部门
    initDept();

}

/*
 * 初始化部门
 */
function initDept() {

    var params = {
        "showpost" : 0
    };

    Supp.ajax({
        "type" : "post",
        "url" : "/service/mobile/proxy/r/service/eip/company/getTreeDataOperResult",
        "data" : params,
        "isAuto" : false,
        "success" : function(data) {
            deptList = data.body.rows;
            //筛选pid为null的数据，即根节点数据
            var rootList = [];
            rootList = jq.map(deptList, function(item) {
                if (!item.pId) {
                    return item;
                }
            });

            currentDeptNode = rootList[0];
            //查询所有子部门
            var sonList = [];
            sonList = jq.map(deptList, function(item) {
                if (item.pId == currentDeptNode.id) {
                    item["checked"] = false;
                    return item;
                }
            });
            currentDeptNode["son"] = sonList;

            //异步查询当前部门的下级所有人员
            getEmpListAllByDeptNode(currentDeptNode.id);

            //部门列表默认显示根节点下的一级部门
            for (var i = 0; i < currentDeptNode.son.length; i++) {
                var node = currentDeptNode.son[i];
                var sonList = [];
                sonList = jq.map(deptList, function(item) {
                    if (item.pId == node.id) {
                        item["checked"] = false;
                        return item;
                    }
                });
                node["son"] = sonList;
                node["emp_all"] = [];
                //异步查询当前部门的下级所有人员
                getEmpListAllByDeptNode(node.id, i);
            };
            empDeptList = currentDeptNode.son;
            vueObj.empDeptList = currentDeptNode.son;

            //得到当前节点下的人员列表
            getEmpListByDeptNode(currentDeptNode.id);
        }
    });

}

//得到部门节点下的人员列表
function getEmpListByDeptNode(deptId) {
    //初始化按部门查询人员数据
    var params = {
        rootdeptid : deptId,
        showpost : true,
        showresigned : 1,
        showathisoutage : 1,
        showSubDeptEmp : false,
        showadministration : 1
    };

    Supp.ajax({
        "type" : "post",
        "url" : "/service/mobile/proxy/r/service/eip/employee/getEmpListOperResult",
        "data" : params,
        "isAuto" : false,
        "success" : function(data) {
            var list = data.body.rows;
            empList = list;
            var selectedList = vueObj.empSelected;

            for (var i = 0; i < selectedList.length; i++) {
                var selEmp = selectedList[i];
                //遍历该list，判断是否存在被选中的人员
                var emp = empList.findByPrimaryKey("empId", selEmp.empId);
                if (emp && emp.empId) {
                    emp["checked"] = true;
                }
            };

            vueObj.empList = empList;
        }
    });

}

//得到部门节点下的所有下级人员列表
function getEmpListAllByDeptNode(deptId, index) {
    var pageSize = 1000;
    if (index == undefined) {
        pageSize = 7;
    }
    //初始化按部门查询人员数据
    var params = {
        rootdeptid : deptId,
        showpost : true,
        showresigned : 1,
        pageNo : 1,
        showathisoutage : 1,
        showSubDeptEmp : true,
        showadministration : 1
    };

    Supp.ajax({
        "type" : "post",
        "url" : "/service/mobile/proxy/r/service/eip/employee/getEmpListOperResult",
        "data" : params,
        "index" : index,
        "isAuto" : false,
        "success" : function(data) {
            var list = data.body.rows;
            if (this.index == undefined) {
                vueObj.sonDeptEmpNum = data.body.rowCount;
            } else {
                vueObj.empDeptList[this.index].emp_all = list;
            }

        }
    });

}

function slideCheckedDiv() {
    var wrapperWidth = $(".footer_checked_div .mui-scroll-wrapper").width();
    var scrollWidth = $(".footer_checked_div .mui-scroll").width();
    if (wrapperWidth < scrollWidth) {
        $(".footer_checked_div .mui-scroll").css("-webkit-transform", "translate3d(" + (wrapperWidth - scrollWidth) + "px, 0px, 0px) translateZ(0px)");
    } else {
        $(".footer_checked_div .mui-scroll").css("-webkit-transform", "translate3d(0px, 0px, 0px) translateZ(0px)");
    }
}

